package com.sls.nzdapplication.ui.activity;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.bin.david.form.core.SmartTable;
import com.bin.david.form.data.column.Column;
import com.bin.david.form.data.style.FontStyle;
import com.bin.david.form.data.table.TableData;
import com.hmy.popwindow.PopItemAction;
import com.hmy.popwindow.PopWindow;
import com.huawei.hms.hmsscankit.ScanUtil;
import com.huawei.hms.ml.scan.HmsScan;
import com.huawei.hms.ml.scan.HmsScanAnalyzerOptions;
import com.markfrain.formview.view.FormEditView;
import com.sls.nzdapplication.R;
import com.sls.nzdapplication.app.AppActivity;
import com.sls.nzdapplication.db.utils.MeterBoxUtil;
import com.sls.nzdapplication.db.utils.MeterUtil;
import com.sls.nzdapplication.db.utils.UserDataUtil;
import com.sls.nzdapplication.model.DyWorkInfo;
import com.sls.nzdapplication.model.Meter;
import com.sls.nzdapplication.model.MeterBox;
import com.sls.nzdapplication.model.ShowUserInfo;
import com.sls.nzdapplication.model.User;
import com.sls.nzdapplication.ui.custom.adapter.SearchAdapter;
import com.sls.nzdapplication.util.DeviceUtils;
import com.sls.nzdapplication.util.Utils;
import com.sls.nzdapplication.util.UuidUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import es.dmoral.toasty.Toasty;

/**
 * 这个类是一个电表箱详情页面，主要功能是添加电表，删除电表，编辑电表，扫码添加电表，显示电表列表。
 * 在页面上有一个表格，用于显示电表列表，表格的每一行代表一个电表，每一列代表电表的一个属性，如电表号、用户名称、行号、列号等。
 * 在页面上还有一个下拉框，用于选择电表的查询方式，如用户表号、用户名称、用户编号、用户地址等。
 * 在页面上还有一个文本框，用于输入电表的查询条件，如用户表号、用户名称、用户编号、用户地址等。
 * 在页面上还有一个按钮，用于添加电表，点击按钮后会将输入的电表信息添加到电表列表中。
 * 在页面上还有一个按钮，用于扫码添加电表，点击按钮后会打开扫码界面，扫描电表二维码后会将电表信息添加到电表列表中。
 * */
public class DbDetailActivity extends AppActivity implements View.OnClickListener {
    private RelativeLayout relativeLayout;

    private TextView dbRowNumberView;

    private TextView dbColumnNumberView;

    private AutoCompleteTextView tmView;

    private ImageView dbAddBtnView;

    private ImageView saoMaBtn;

    private MeterUtil meterUtil;

    private MeterBoxUtil meterBoxUtil;

    private String boxId;

    private List<Meter> meterList;

    private MeterBox meterBox;

    private int rows,cols;


    private int padding = 30;

    private int one_row = 1;

    private int one_col = 1;

    private LinearLayout dataListView;

    PopWindow popupWindow;

    private Spinner spinner;

    private String dbNameType = "";

    private List<User> userList;

    private UserDataUtil userDataUtil;

    public static final String SD_APP_DIR_NAME = "NZDAPP";

    private String autopath = Environment.getExternalStorageDirectory().getAbsolutePath()
            + "/" + SD_APP_DIR_NAME + "/"; // 外部SD卡上的根目录

    private String logPath = autopath+"log";

    // 1.声明常量
    public static final int DEFAULT_VIEW = 0x22;
    private static final int REQUEST_CODE_SCAN = 0X01;

    SmartTable<ShowUserInfo> table;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_db_detail;
    }

    @Override
    protected void initView() {
        relativeLayout = findViewById(R.id.box_main);
        dbRowNumberView = findViewById(R.id.db_row_number);
        dbColumnNumberView = findViewById(R.id.db_column_number);
        tmView = findViewById(R.id.tm_name);
        tmView.setThreshold(1);
        dbAddBtnView = findViewById(R.id.add_db_btn);
        relativeLayout = findViewById(R.id.box_main);
        table = findViewById(R.id.user_data);

        table.getConfig().setShowXSequence(false);
        table.getConfig().setShowYSequence(false);
        table.getConfig().setShowTableTitle(false);
        table.getConfig().setColumnTitleStyle (new FontStyle(30, getResources().getColor(R.color.colorPrimaryDark)));
        table.getConfig().setMinTableWidth(getActivity().getWindowManager().getDefaultDisplay().getWidth());
        spinner = findViewById(R.id.dbname_type);
        saoMaBtn = findViewById(R.id.add_saoma);
        dbAddBtnView.setOnClickListener(this);
        saoMaBtn.setOnClickListener(this);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                dbNameType = adapterView.getSelectedItem().toString();
                initDbNameSelect();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
    }



    private void initDbNameSelect(){
        List<String> names = new ArrayList<>();
        for(User user:userList){
            switch (dbNameType){
                case "用户表号":
                    if(user.getBarCode()!=null && user.getBarCode().length()>0){
                        names.add(user.getBarCode());
                    }
                    saoMaBtn.setVisibility(View.VISIBLE);
                    break;
                case "用户名称":
                    if(user.getUsername()!=null && user.getUsername().length()>0){
                        names.add(user.getUsername());
                    }
                    saoMaBtn.setVisibility(View.INVISIBLE);
                    break;
                case "用户编号":
                    if(user.getUserCode()!=null && user.getUserCode().length()>0){
                        names.add(user.getUserCode());
                    }
                    saoMaBtn.setVisibility(View.INVISIBLE);
                    break;
                case "用户地址":
                    if(user.getAddress()!=null && user.getAddress().length()>0){
                        System.err.println(user.getAddress());
                        names.add(user.getAddress());
                    }
                    saoMaBtn.setVisibility(View.INVISIBLE);
                    break;
            }
        }
        SearchAdapter<String> arrayAdapter = new SearchAdapter<String>(DbDetailActivity.this, android.R.layout.simple_dropdown_item_1line, names,SearchAdapter.ALL);
        tmView.setAdapter(arrayAdapter);
    }

    private void saveData(){
        int row = one_row;
        int column = one_col;
        String code = tmView.getText().toString();
        if(code.equals("")){
            Toasty.error(getApplicationContext(), "内容不能为空", Toast.LENGTH_LONG, true).show();
            return;
        }
        User myuser=null;
        switch (dbNameType){
            case "用户表号":
                myuser = userDataUtil.queryUserByAreaIdAndUserCode(meterBox.getAreaId(),code);
                break;
            case "用户名称":
                myuser = userDataUtil.queryUserByAreaIdAndUsername(meterBox.getAreaId(),code);
                break;
            case "用户编号":
                myuser = userDataUtil.queryUserByAreaIdAndUserC(meterBox.getAreaId(),code);
                break;
            case "用户地址":
                myuser = userDataUtil.queryUserByAreaIdAndAddress(meterBox.getAreaId(),code);
                break;
        }

        if(dbNameType.equals("用户地址") && myuser==null){
            Toasty.error(getApplicationContext(), "该地址无表箱，请选择其他录入", Toast.LENGTH_LONG, true).show();
            return;
        }

        if(myuser !=null && meterUtil.queryMeterByMeterCode(myuser.getBarCode())!=null){
            Toasty.error(getApplicationContext(), "该电表号已存在", Toast.LENGTH_LONG, true).show();
            return;
        }
        if(meterUtil.queryMeterByBoxIdAndRowAndColumn(boxId,row,column)!=null){
            Toasty.error(getApplicationContext(), "该位置已有电表", Toast.LENGTH_LONG, true).show();
            return;
        }

        Meter meter = new Meter();
        meter.setId(UuidUtils.getStringID());
        meter.setBoxId(boxId);
        meter.setColumnNum(column);
        meter.setRowNum(row);
        meter.setMatch(false);
        if(myuser!=null){
            meter.setMeterCode(myuser.getBarCode());
            meter.setUserCode(myuser.getUserCode());
            meter.setUsername(myuser.getUsername());
        }else {
            switch (dbNameType){
                case "用户表号":
                    meter.setMeterCode(code);
                    break;
                case "用户名称":
                    meter.setUsername(code);
                    break;
                case "用户编号":
                    meter.setUserCode(code);
                    break;

            }
        }

        meterUtil.insertMeter(meter);
        Toasty.success(getApplicationContext(), "添加成功", Toast.LENGTH_LONG, true).show();
        refreshData();
        refreshcR();

    }

    private void refreshcR(){
        if(one_col==cols && one_row == rows){
            return;
        }
        if(one_col<cols){
            one_col+=1;
            dbColumnNumberView.setText(String.valueOf(one_col));
        }else{
            if(one_row<rows){
                one_row+=1;
                one_col=1;
                dbRowNumberView.setText(String.valueOf(one_row));
                dbColumnNumberView.setText(String.valueOf(one_col));
            }
        }
    }

    private void refreshData(){
        meterList = meterUtil.queryMetersByBoxId(boxId);
        showData(meterList);
        showDb();
    }

    /**
     * 数据
     */
    private void showData(List<Meter> titleData) {
        table.setTableData(null);
        List<ShowUserInfo> userInfos = new ArrayList<>();
        for (int i = 0; i < titleData.size(); i++) {
            final Meter meter = titleData.get(i);
            ShowUserInfo showUserInfo = new ShowUserInfo();
            showUserInfo.setXh(String.valueOf(i+1));
            showUserInfo.setTxm(meter.getMeterCode());
            showUserInfo.setUsername(meter.getUsername());
            showUserInfo.setCol(String.valueOf(meter.getColumnNum()));
            showUserInfo.setRow(String.valueOf(meter.getRowNum()));
            showUserInfo.setCheck("匹配");
            userInfos.add(showUserInfo);
        }

        if(userInfos.size()>0){
            table.setVisibility(View.VISIBLE);
            table.setData(userInfos);
            table.getTableData().setOnRowClickListener(new TableData.OnRowClickListener<ShowUserInfo>() {
                @Override
                public void onClick(Column column, ShowUserInfo showUserInfo, int col, int row) {
                    new PopWindow.Builder(DbDetailActivity.this)
                            .setStyle(PopWindow.PopWindowStyle.PopUp)
                            .setTitle("请选择你要的操作")
                            .addItemAction(new PopItemAction("编辑", PopItemAction.PopItemStyle.Normal, new PopItemAction.OnClickListener() {
                                @Override
                                public void onClick() {
                                    dbDetail(titleData.get(row));
                                }
                            }))
                            .addItemAction(new PopItemAction("删除", PopItemAction.PopItemStyle.Warning, new PopItemAction.OnClickListener() {
                                @Override
                                public void onClick() {
                                    deleteDb(titleData.get(row));
                                }
                            }))
                            .addItemAction(new PopItemAction("取消", PopItemAction.PopItemStyle.Cancel))
                            .show();
                }
            });
        }else {
            table.setVisibility(View.GONE);
        }

    }

    @Override
    protected void initData() {
        meterUtil = new MeterUtil(getApplicationContext());
        meterBoxUtil = new MeterBoxUtil(getApplicationContext());
        Intent intent = getIntent();
        boxId = intent.getStringExtra("boxId");
        meterBox = meterBoxUtil.listOneMeterBox(boxId);
        rows = meterBox.getRow();
        cols = meterBox.getColumn();
        refreshData();
        userDataUtil = new UserDataUtil(getApplicationContext());
        userList = userDataUtil.queryUserByAreaId(meterBox.getAreaId());
    }

    @Override
    public void onRightClick(View view) {

    }

    @Override
    public void onClick(View view) {
        if(view == dbAddBtnView){
            saveData();
        }
        if(view == saoMaBtn){
            try {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    this.requestPermissions(
                            new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE},
                            DEFAULT_VIEW);
                }
            }catch (Exception e){
                Utils.writeTxtToFile(e.getMessage(),logPath,"/log.txt");
            }

        }
    }

    private void dbDetail(Meter meter){
        View dbview = View.inflate(getApplicationContext(), R.layout.meter_detail_layout, null);
        FormEditView usernameView = dbview.findViewById(R.id.meter_user_name);
        FormEditView usercodeView = dbview.findViewById(R.id.meter_user_code);
        FormEditView metercodeView = dbview.findViewById(R.id.meter_code);
        usernameView.getContent().setText(meter.getUsername()==null?"":meter.getUsername());
        usercodeView.getContent().setText(meter.getUserCode()==null?"":meter.getUserCode());
        metercodeView.getContent().setText(meter.getMeterCode()==null?"":meter.getMeterCode());
        popupWindow= new PopWindow.Builder(DbDetailActivity.this)
                .setStyle(PopWindow.PopWindowStyle.PopAlert)
                .setMessage("编辑电表内容")
                .addContentView(dbview)
                .setIsShowCircleBackground(false)
                .addItemAction(new PopItemAction("确定", PopItemAction.PopItemStyle.Normal, new PopItemAction.OnClickListener() {
                    @Override
                    public void onClick() {
                        if(!usernameView.getValue().equals("")){
                            meter.setUsername(usernameView.getValue());
                        }
                        if(!usercodeView.getValue().equals("")){
                            meter.setUserCode(usercodeView.getValue());
                        }if(!metercodeView.getValue().equals("")){
                            meter.setMeterCode(metercodeView.getValue());
                        }
                        new MeterUtil(getApplicationContext()).updateMeter(meter);
                        popupWindow.dismiss();
                        refreshData();
                    }
                }))
                .addItemAction(new PopItemAction("取消", PopItemAction.PopItemStyle.Warning))
                .setPopWindowMarginsF(DeviceUtils.dip2px4View(getApplicationContext(),30), DeviceUtils.dip2px4View(getApplicationContext(),200), DeviceUtils.dip2px4View(getApplicationContext(),30), DeviceUtils.dip2px4View(getApplicationContext(),0))
                .show();
    }

    private void deleteDb(Meter m){
        if(m!=null){
            meterUtil.deleteMeter(m);
            refreshData();
        }
    }

    private void showDb() {
        relativeLayout.removeAllViews();
        MeterBox meterBox = meterBoxUtil.listOneMeterBox(boxId);
        rows = meterBox.getRow();
        cols = meterBox.getColumn();
        float x = 1200/cols;
        float y = 800/rows;
        int dbSize = 0;
        if(Utils.aBigger(x,y)){
            dbSize = new Float(y).intValue()-10;
        }else{
            dbSize = new Float(x).intValue()-10;
        }
        for (int i = 0; i < rows; i++) {
            for(int j = 0; j<cols;j++){
                ImageView imageView = new ImageView(getApplicationContext());
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams((int)mm2dp(Float.valueOf(dbSize)),(int)mm2dp(Float.valueOf(dbSize)));
                imageView.setLayoutParams(layoutParams);
                imageView.setY(mm2dp(padding*(i+1)+dbSize*i));
                imageView.setX(mm2dp(padding*(j+1)+dbSize*j));
                if(meterUtil.queryMeterByBoxIdAndRowAndColumn(boxId,i+1,j+1)==null){
                    imageView.setBackgroundResource(R.drawable.db_nomal);
                }else{
                    imageView.setBackgroundResource(R.drawable.db_ok);
                }

                HashMap<String,Integer> hashMap = new HashMap<>();
                hashMap.put("row",i+1);
                hashMap.put("col",j+1);
                imageView.setTag(hashMap);
                int a = i+1;
                int b = j+1;
                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        HashMap<String,Integer> hashMap = (HashMap<String,Integer>)view.getTag();
                        one_col = hashMap.get("col");
                        one_row = hashMap.get("row");
                        dbRowNumberView.setText(String.valueOf(one_row));
                        dbColumnNumberView.setText(String.valueOf(one_col));

                        if(meterUtil.queryMeterByBoxIdAndRowAndColumn(boxId,a,b)==null){
                            try {
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                    getActivity().requestPermissions(
                                            new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE},
                                            DEFAULT_VIEW);
                                }
                            }catch (Exception e){
                                Utils.writeTxtToFile(e.getMessage(),logPath,"/log.txt");
                            }
                        }
                    }
                });
                relativeLayout.addView(imageView);
            }
        }
    }

    // 3.重写onRequestPermissionsResult方法
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (permissions == null || grantResults == null || grantResults.length < 2 || grantResults[0] != PackageManager.PERMISSION_GRANTED || grantResults[1] != PackageManager.PERMISSION_GRANTED) {
            return;
        }

        if (requestCode == DEFAULT_VIEW) {
            //申请权限之后，调用DefaultView扫码界面
            ScanUtil.startScan(DbDetailActivity.this, REQUEST_CODE_SCAN, new HmsScanAnalyzerOptions.Creator().setHmsScanTypes(HmsScan.ALL_SCAN_TYPE).create());
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        //从onActivityResult返回data中，用 ScanUtil.RESULT作为key值取到HmsScan返回值
        if (requestCode == REQUEST_CODE_SCAN) {
            Object obj = data.getParcelableExtra(ScanUtil.RESULT);
            if (obj instanceof HmsScan) {
                if (!TextUtils.isEmpty(((HmsScan) obj).getOriginalValue())) {
//                    Toasty.info(getApplicationContext(),"编号为："+((HmsScan) obj).getOriginalValue(),Toast.LENGTH_SHORT,true).show();
                    if(meterUtil.queryMeterByMeterCode(((HmsScan) obj).getOriginalValue())!=null){
                        Toasty.error(getApplicationContext(), "该电表号已存在", Toast.LENGTH_LONG, true).show();
                        return;
                    }else{
                        tmView.setText(((HmsScan) obj).getOriginalValue());
                    }
                }
                return;
            }
        }
    }


    private float mm2dp(float mm){
        return mm/2;
    }

}